Netty 解决消息被截断问题

Netty 解决消息被截断问题

netty默认发送的长度为1024,超过这个长度的数据会被拆分成多个包发送,为了解决这个问题,netty提供了多个解码编码器供我们使用,这里使用LineBasedFrameDecoder。

首先看server端增加的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 65535, 65535))
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel (SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandler());
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

// 绑定端口,开始接收进来的连接
ChannelFuture f = b.bind(port).sync(); // (7)

// 等待服务器 socket 关闭 。
// 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。
f.channel().closeFuture().sync();

其中重点是

1
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 65535, 65535))

1
2
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());

然后是client端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
client.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(64, 65535, 65535))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel (SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyClientHandler());
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
}
});

//绑定端口, 异步连接操作
future = client.connect(host, port).sync();

//等待客户端连接端口关闭
future.channel().closeFuture().sync();
Thanks!